<link rel="import" href="../bower_components/app-route/app-route.html">
<link rel="import" href="../bower_components/mist-list/mist-list.html">
<link rel="import" href="../bower_components/paper-fab/paper-fab.html">

<link rel="import" href="teams/team-page.html">
<link rel="import" href="teams/team-actions.html">
<link rel="import" href="teams/member-page.html">
<link rel="import" href="teams/members-add.html">
<link rel="import" href="teams/member-add-in-teams.html">
<link rel="import" href="teams/team-add.html">
<link rel="import" href="helpers/mist-lists-behavior.html">


<dom-module id="page-teams">
    <template>
        <style include="shared-styles">
            [hidden] {
                display: none !important;
            }
            mist-list {
                font-size: 14px;
            }
            mist-list[selectable] ::slotted(vaadin-grid-table-row) {
                cursor: pointer;
            }
        </style>
        <app-route route="{{route}}" pattern="/:team" data="{{data}}"></app-route>
        <template is="dom-if" if="[[_isListActive(route.path)]]" restamp>
            <team-actions id="actions" items="[[selectedItems]]" org="[[model.org.id]]" actions="{{actions}}">
                <mist-list selectable resizable column-menu multi-sort 
                    apiurl="/api/v1/teams"
                    id="teamsList"
                    name="Teams"
                    primary-field-name="id"
                    frozen=[[_getFrozenColumn()]]
                    visible=[[_getVisibleColumns()]]
                    selected-items="{{selectedItems}}"
                    sort-order=[[sortOrder]]
                    renderers=[[_getRenderers()]]
                    route={{route}}
                    items="[[model.teamsArray]]"
                    actions=[[actions]]
                    user-filter=[[model.sections.teams.q]]
                    filter-method="[[_isMemberOfFilter()]]"
                    filtered-items-length="{{filteredItemsLength}}"></mist-list>
            </team-actions>
        </template>
        <team-page id="teamPage" model="[[model]]" team="[[_getTeam(data.team, model.teams)]]" resource-id="[[data.team]]" section="[[model.sections.teams]]" hidden$=[[!_isDetailsPageActive(route.path)]] rbac=[[rbac]] billing="[[billing]]" cta=[[cta]] email=[[email]] docs=[[docs]]></team-page>
        <members-add model="[[model]]" params="[[data]]" section="[[model.sections.teams]]" hidden$=[[!_isAddMembersPageActive(route.path)]]></members-add>
        <member-add-in-teams model="[[model]]" params="[[data]]" section="[[model.sections.teams]]" hidden$=[[!_isAddMemberPageActive(route.path)]]></member-add-in-teams>
        <team-add id="isTeamsPage" organization="[[model.org]]" rbac=[[rbac]]></team-add>
        <div class="absolute-bottom-right" hidden$=[[!_showAddTeam(route.path,model.user)]]>
            <paper-fab id="isTeams" icon="add" on-tap="_addTeam"></paper-fab>
        </div>
    </template>
    <script>
    Polymer({

        is: 'page-teams',
        behaviors: [
            mistListsBehavior,
            rbacBehavior
        ],

        properties: {
            model: {
                type: Object
            },
            ownership: {
                type: Boolean
            },
            route: {
                type: Object
            },
            actions: {
                type: Array,
                notify: true
            },
            selectedItems: {
                type: Array,
                value: function() { return [] }
            },
            rbac: {
                type: Boolean,
                value: false
            },
            docs: {
                type: Boolean,
                value: false
            }
        },

        listeners: {},
        _isDetailsPageActive: function(path) {
            if (path && path != '/+add' && this.$.teamPage)
                this.$.teamPage.updateState();
            return path && !path.endsWith('+add');
        },
        _isAddMembersPageActive: function(path) {
            return path != '/+add' && path.endsWith('+add');
        },
        _isAddMemberPageActive: function(path) {
            return path == '/+add';
        },
        _isListActive: function(path) {
            return !path;
        },
        _isMemberOfFilter: function() {
            var _this = this;
            return {
                'apply': function(item, query) {
                    var q = query.slice(0) || '',
                        filterOwner = query.indexOf('owner:') > -1,
                        ownerRegex = /owner:(\S*)\s?/;

                    if (filterOwner && q) {
                        if (ownerRegex.exec(q).length) {
                            var owner = ownerRegex.exec(q)[1];
                            if (owner) {
                                if (owner == "$me") {
                                    if (!item.members.length || item.members.indexOf(_this.model.user.id) == -1)
                                        return false;
                                } else {
                                    var ownerObj = _this.model.membersArray.find(function(m) {
                                        return [m.name, m.email, m.username, m.id].indexOf(owner) > -1;
                                    });
                                    if (!ownerObj || (!item.members.length || item.members.indexOf(ownerObj.id) == -1))
                                        return false;
                                }
                                q = q.replace('owner:', '').replace(owner, '');
                                return q;
                            }
                        }
                    }
                    return query;
                }
            }
        },
        _hasNoSelectedItems: function() {
            return !(this.selectedItems && this.selectedItems.length);
        },
        _getTeam: function(id) {
            if (this.model.teams && id)
                return this.model.teams[id];
        },

        _getFrozenColumn: function() {
            return ['name'];
        },

        _getVisibleColumns: function() {
            return ['description', 'members'];
        },

        _getRenderers: function(teams, members) {
            var _this = this;
            return {
                'name': {
                    'body': function(item, row) {
                        if (row.parent && _this.model && _this.model.org && _this.model.org.parent_org_name) {
                            var ret = "[" + _this.model.org.parent_org_name + "] <strong>" + item + "</strong>";
                            return ret;
                        }
                        return "<strong class='name'>" + item + "</strong>";
                    }
                },
                'members': {
                    'body': function(item, row) {
                        if (_this.model && _this.model.members && item && item.length && item.length > 0) {
                            var names = item.map(function(i) {
                                if (_this.model.members[i])
                                    var displayName = _this.model.members[i].name || _this.model.members[i].email || _this.model.members[i].username;
                                return " " + displayName;
                            })
                            var ret = names;
                            return ret;
                        }
                        return item;
                    }
                }
            };
        },

        _addTeam: function(e) {
            var dialog = this.shadowRoot.querySelector('team-add#isTeamsPage');
            dialog.openDialog();
        },

        selectAction: function(e) {
            e.stopImmediatePropagation();
            if (this.shadowRoot.querySelector('#teamsList')) {
                this.shadowRoot.querySelector('#teamsList').shadowRoot.querySelector('#actions').selectAction(e);
            }
        },

        _showAddTeam: function(path, user) {
            return this.model && this._isListActive(path) && this.check_perm('add','key', null, this.model.org, this.model.user);
        }

    });
    </script>
</dom-module>